<template>
  <div class="common-layout">
    <el-container>
      <el-header height="2.2rem" >
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            background-color="#545c64"
            text-color="#ffd04b"
            active-text-color=""
 
          >
              <el-menu-item index="0" >
              <span class="iconfont" >&#xe607; 采集参估</span>
              </el-menu-item>
              <el-menu-item index="5" @click="goToPage('/CollectPage')">
                <h2>多通道同步采集</h2>
              </el-menu-item>
              <el-menu-item index="6" @click="goToPage('/DetectPage')">
                <h2>信号检测</h2>
              </el-menu-item>
              <!-- <el-menu-item index="7" @click="goToPage('/EstimatePage')">
                <h2>参数估计</h2>
              </el-menu-item> -->
              <el-menu-item index="8" @click="goToPage('/LoadBalance')">
                <h2>参估设备负载均衡</h2>
              </el-menu-item>
              <div class="flex-grow" />
              <!-- <el-menu-item index="3">
                <el-button class="startMultiPaths" type="success"  @click="startMultiPaths">
                  <template #icon>
                    <el-icon><Open /></el-icon>
                  </template>
                  批量开始
                </el-button>
              </el-menu-item>
              <el-menu-item index="4">
                <el-button class="stopMultiPaths" type="danger"  @click="stopMultiPaths">
                  <template #icon>
                    <el-icon><TurnOff /></el-icon>
                  </template>
                  批量停止
                </el-button>
              </el-menu-item>               -->
              <el-menu-item index="1" @click="openDialog('data-import',-1)">
                <el-button class="importJson" type="info" plain >
                    <template #icon>
                      <el-icon><Upload /></el-icon>
                    </template>
                    导入Excel
                  </el-button>
              </el-menu-item>
              <el-menu-item index="2" @click="openDialog('excel-export',-2)">
                <el-button class="export" type="info" plain >
                  <template #icon>
                    <el-icon><Download /></el-icon>
                  </template>
                  导出Excel
                </el-button>
              </el-menu-item>
      </el-menu>
      </el-header>
      <el-main>
        <router-view></router-view>
      </el-main>    
    </el-container>
  </div>
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    :width="dialog.width"
    append-to-body
    center
  >
    <el-form
      v-if="dialog.type === 'data-import'"
      label-width="100px"
    >
      <el-form-item label="Excel文件">
        <el-upload
          ref="uploadRef"
          action=""
          drag
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :limit="1"
          :auto-upload="false"
          :file-list="importData.fileList"
          :on-change="handleFileChange"
          :on-exceed="handleFileExceed"
          :show-file-list="true"
        >
          <el-icon class="el-icon--upload">
            <i-ep-upload-filled />
          </el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <template #tip>
            <div>xls/xlsx files</div>
          </template>
        </el-upload>
                
      </el-form-item>      
    </el-form>
    <el-form
      v-else-if="dialog.type === 'excel-export'"
      label-width="100px"
    >
      <el-input v-model="exportExcelName"></el-input>
    </el-form>
    <template #footer v-if="dialog.type === 'excel-export'">
      <span class="dialog-footer">
        <el-button @click="handleExportExcel" type="primary">确认</el-button>
        <el-button @click="cancelModify">取消</el-button>
      </span>
    </template>
    <template #footer v-else-if="dialog.type === 'data-import'">
        <span class="dialog-footer">
          <el-button @click="confirmImport" type="primary">确认</el-button>
          <el-button @click="cancelModify">取消</el-button>
        </span>
    </template>
  </el-dialog>
</template>
  
<script lang="ts" setup>
    import '../assets/font_detect/iconfont.css'
    import { ref, reactive,onMounted } from 'vue'  
    import {useRouter} from 'vue-router'
    import { ElTable } from 'element-plus'
    import { Download,Upload,Open,TurnOff } from '@element-plus/icons-vue'
    import { genFileId } from 'element-plus'
    import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
    import { readExcel } from '../apis/importExcel'
    import ExcelJS from 'exceljs'
    import EstimateApi from '../apis/estimateHttp.js'
    import DetectApi from '../apis/detectHttp.js'
    import CollectApi from '../apis/collectHttp.js'
    import { send } from 'vite'
    import XLSX  from 'xlsx'
    import { ElMessage } from 'element-plus'
    //路由切换
    const router = useRouter()
    const goToPage = (path) => {
      router.push(path)
    }

    onMounted(() => {  
      router.push('/CollectPage')//默认跳转到采集页面
    })
    const uploadRef = ref<UploadInstance>()

    const exportExcelName = ref("collectEstimate")
    let sendExcel2Collect = []
    let sendExcel2Detect = []
    //确认导入excel
    const confirmImport = async () => {
      
      //调用三个接口传输数据
      CollectApi.postAllData(sendExcel2Collect)
      DetectApi.postExcelData(sendExcel2Detect)
      // EstimateApi.postExcelData(sendExcel2Collect)
    
      dialog.visible = false
    }
    const activeIndex = ref('1')

    const dialog = reactive({
      visible:false,
      type:"singlePath-form",
      width:500,
      title:""
    })  
    
    //取消修改
    const cancelModify = () => {  
      dialog.visible = false
    }
    const currentRow = ref()
    const singleTableRef = ref<InstanceType<typeof ElTable>>()
    
    //TODO 编辑某行弹出弹窗  
    async function openDialog(type:string,id:number){
      dialog.visible = true;
      dialog.type = type;
          
      if(id >= 0 && id <= 63){
           
      }else if(id === -1){
        dialog.title = "选择导入配置文件"
      }else if(id === -2){
        dialog.title = "设置导出excel文件名"
      }
    }
    //导出excel文件
    const handleExportExcel = async () => {
      const collectConfig = await CollectApi.getCollectConfig()
      const detectConfig = await DetectApi.getAllData()
      const estimateConfig = await EstimateApi.getAllData()
      if("collectConfig" in collectConfig && "all" in detectConfig
      &&"all" in estimateConfig)
      {
        const allConfig = collectConfig["collectConfig"]
      
        let tableData = [
          ['DDC通道号','通道1频点','通道2频点','通道3频点','通道4频点',
          '通道1增益','通道2增益','通道3增益','通道4增益','定时启动时间','文件大小',
          '检测通道','检测算法类型','检测带宽','采样率',
          '参估带宽','插值倍数','相关长度','参估算法','频差范围','时差范围','判决门限'],
        ]
      
        allConfig.forEach((item) => {
          let strTime = item.touch_time
          const rowData = [
            item.pathid,
            item.ch0_freq,
            item.ch1_freq,
            item.ch2_freq,
            item.ch3_freq,
            item.ch0_gain,
            item.ch1_gain,
            item.ch2_gain,
            item.ch3_gain,
            item.touch_time = replaceAll(strTime,":","-"),
            item.file_size
          ]
          for(let i= 0;i<detectConfig["all"].length;i++){
            if(detectConfig["all"][i].pathid == item.pathid){
              rowData.push(detectConfig["all"][i].chid_primary)
              rowData.push(detectConfig["all"][i].detect_algotype)
              rowData.push(detectConfig["all"][i].detect_bandwidth)
              rowData.push(detectConfig["all"][i].sample_rate)
              break
            }
          } 
          for(let j=0;j<estimateConfig["all"].length;j++){
            if(estimateConfig["all"][j].pathid == item.pathid){
              rowData.push(estimateConfig["all"][j].estimate_bandwidth)
              rowData.push(estimateConfig["all"][j].upFactor)
              rowData.push(estimateConfig["all"][j].related_Len)
              rowData.push(estimateConfig["all"][j].estimate_algotype)
              rowData.push(estimateConfig["all"][j].fre_range)
              rowData.push(estimateConfig["all"][j].time_range)
              rowData.push(estimateConfig["all"][j].judege_threshold)
            }
          }
          
          tableData.push(rowData)
        });
        
        //excel配置
        let worksheet = XLSX.utils.aoa_to_sheet(tableData)
        let bookNew = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(bookNew,worksheet,'Sheet1')
        XLSX.writeFile(bookNew, exportExcelName.value + '.xlsx')
        }
        
      dialog.visible = false
    }
    //导出json文件
    const handleExportJson = async () =>{
      //TODO 调用接口请求配置文件数据
      const fileName = "config.json"
      const fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=uft-8"
      const data = JSON.stringify(sendExcel2Collect)
      const blob = new Blob([data],{type:fileType})
      const downloadUrl = window.URL.createObjectURL(blob)
      const downloadLink = document.createElement("a")
      downloadLink.href = downloadUrl
      downloadLink.download = fileName

      document.body.appendChild(downloadLink)
      downloadLink.click()

      document.body.removeChild(downloadLink)
      window.URL.revokeObjectURL(downloadUrl)
    }
    // 用户导入数据
    const importData = reactive({
      deptId: undefined,
      file: undefined,
      fileList: [],
    });
    interface detectDataType {  
        "path_id":number,  
        "collect_column": {
            "ch0_freq": number,
            "ch1_freq": number,
            "ch2_freq": number,
            "ch3_freq": number,
            "sample_rate": number
          },
          "detect_column": {
              "chid_primary": number,
              "detect_algotype": number,
              "detect_bandwidth": number
          },
            "estimate_column": {
                "estimate_algotype": number,
                "estimate_bandwidth": number,
                "freq_range": number,
                "judge_threshold": number,
                "related_len": number,
                "time_range": number,
                "up_factor": number
            }                      
    }
    //excel文件改变
    const handleFileChange = async (file:any) => {
      if(sendExcel2Collect.length > 0){//每一次导入清空上一次发给采集的数组
        sendExcel2Collect.splice(0,sendExcel2Collect.length)
      }
      
      if(sendExcel2Detect.length > 0){//每一次导入清空上一次发给检测的数组
        sendExcel2Detect.splice(0,sendExcel2Detect.length)
      }
      // 读取上传的Excel文件
      const workbook = new ExcelJS.Workbook();
      await workbook.xlsx.load(file.raw);
      const jsonData = []
      // if( sendExcel2Collect.length > 0) sendExcel2Collect.splice(0,sendExcel2Collect.length)//每一次导入清空上一次的数据
      // 获取第一个工作表
      const worksheet = workbook.getWorksheet(1);
 
      // 读取数据并转换为JSON格式
      worksheet.eachRow({ includeEmpty: true }, function(row, rowNumber) {
        if (rowNumber !== 1) { // 排除表头行
          let rowData = {};
          row.eachCell({ includeEmpty: true }, function(cell, colNumber) {
            // 使用单元格的列号作为JSON对象的键
            rowData[colNumber] = cell.value;
          });
          jsonData.push(rowData)
        }
      });
      
      // excel的JSON数据转为对应字段和格式
      let paths = [] //存储所有收到的pathid判断有无重复
      let sameCount = 0
      jsonData.forEach((item) => {
        let oneRow2Collect = {
          "pathid":0,
          "ch0_freq":0,
          "ch1_freq":0,
          "ch2_freq":0,
          "ch3_freq":0,
          "ch0_gain":0,
          "ch1_gain":0,
          "ch2_gain":0,
          "ch3_gain":0,
          "touch_time":"00:00",
          "file_size":0,
          "chid_primary":0,
          "detect_algotype":0,
          "detect_bandwidth":5000,
          "sample_rate":96000,
          "estimate_bandwidth":5000,
          "upFactor":0,
          "related_Len":0,
          "estimate_algotype":0,
          "fre_range":0,
          "time_range":0,
          "judege_threshold":0
        }
        let oneRow2Detect:detectDataType = {
          "path_id":0,  
          "collect_column": {
            "ch0_freq": 0,
            "ch1_freq": 0,
            "ch2_freq": 0,
            "ch3_freq": 0,
            "sample_rate": 0
          },
          "detect_column": {
              "chid_primary": 0,
              "detect_algotype": 0,
              "detect_bandwidth": 0
          },
            "estimate_column": {
                "estimate_algotype": 0,
                "estimate_bandwidth": 0,
                "freq_range": 0,
                "judge_threshold": 0,
                "related_len": 0,
                "time_range": 0,
                "up_factor": 0
            }            
        }
        if(item[1] < 64 && item[1] >= 0 && (item[2] != null || item[3] != null || item[4] != null || item[5] != null)){
          if(paths.length === 0){//数据为空时直接Push进去一个
            paths.push(item[1])
            oneRow2Collect.pathid = Number(item[1])
            oneRow2Collect.ch0_freq = Number(item[2])
            oneRow2Collect.ch1_freq = Number(item[3])
            oneRow2Collect.ch2_freq = Number(item[4])
            oneRow2Collect.ch3_freq = Number(item[5])
            oneRow2Collect.ch0_gain = Number(item[6])
            oneRow2Collect.ch0_gain = Number(item[6])
            oneRow2Collect.ch1_gain = Number(item[7])
            oneRow2Collect.ch2_gain = Number(item[8])
            oneRow2Collect.ch3_gain = Number(item[9])
            let strTime = String(item[10])
            oneRow2Collect.touch_time = replaceAll(strTime,"-",":")
              // strTime = strTime.replace("时",":")
              // strTime = strTime.replace("分",":")
              // strTime = strTime.replace("秒",":")
            oneRow2Collect.file_size = Number(item[11])
            oneRow2Collect.chid_primary = item[12]
            oneRow2Collect.detect_algotype = item[13]
            oneRow2Collect.detect_bandwidth = item[14]
            oneRow2Collect.sample_rate = item[15]
            oneRow2Collect.estimate_bandwidth = item[16]
            oneRow2Collect.upFactor = item[17]
            oneRow2Collect.related_Len = item[18]
            oneRow2Collect.estimate_algotype = item[19]
            oneRow2Collect.fre_range = item[20]
            oneRow2Collect.time_range = item[21]
            oneRow2Collect.judege_threshold = item[22]              
            sendExcel2Collect.push(oneRow2Collect)
            
            oneRow2Detect.path_id = Number(item[1])
            oneRow2Detect.collect_column.ch0_freq = Number(item[2])
            oneRow2Detect.collect_column.ch1_freq = Number(item[3])
            oneRow2Detect.collect_column.ch2_freq = Number(item[4])
            oneRow2Detect.collect_column.ch3_freq = Number(item[5])
            oneRow2Detect.collect_column.ch0_gain = Number(item[6])
            oneRow2Detect.collect_column.ch1_gain = Number(item[7])
            oneRow2Detect.collect_column.ch2_gain = Number(item[8])
            oneRow2Detect.collect_column.ch3_gain = Number(item[9])
            oneRow2Detect.collect_column.touch_time = replaceAll(strTime,"-",":")
            oneRow2Detect.collect_column.file_size = Number(item[11])
            oneRow2Detect.detect_column.chid_primary = item[12]
            oneRow2Detect.detect_column.detect_algotype = item[13]
            oneRow2Detect.detect_column.detect_bandwidth = item[14]
            oneRow2Detect.collect_column.sample_rate = item[15]
            oneRow2Detect.estimate_column.estimate_bandwidth = item[16]
            oneRow2Detect.estimate_column.up_factor = item[17]
            oneRow2Detect.estimate_column.related_len = item[18]
            oneRow2Detect.estimate_column.estimate_algotype = item[19]
            oneRow2Detect.estimate_column.freq_range = item[20]
            oneRow2Detect.estimate_column.time_range = item[21]
            oneRow2Detect.estimate_column.judge_threshold = Number(item[22])
            sendExcel2Detect.push(oneRow2Detect)
        } //数组为空时直接插入
        else if(paths.length > 0){ //数组个数大于0时需要判断有无重复
          for(let i=0;i<paths.length;i++){
            if(paths[i] === item[1] || null === item[1]) //遍历通道ID过滤掉重复或者为null的，才继续下一步
            {
                sameCount++
                ElMessage({
                  message:"Excel表中存在重复ID或者ID为空的通道,已过滤掉",
                  type:'warning'
                })
                break
            }
          }
          if(sameCount === 0){ //如果没有相同的通道号
              paths.push(item[1])
              oneRow2Collect.pathid = Number(item[1])
              oneRow2Collect.ch0_freq = Number(item[2])
              oneRow2Collect.ch1_freq = Number(item[3])
              oneRow2Collect.ch2_freq = Number(item[4])
              oneRow2Collect.ch3_freq = Number(item[5])
              oneRow2Collect.ch0_gain = Number(item[6])
              oneRow2Collect.ch0_gain = Number(item[6])
              oneRow2Collect.ch1_gain = Number(item[7])
              oneRow2Collect.ch2_gain = Number(item[8])
              oneRow2Collect.ch3_gain = Number(item[9])
              let strTime = String(item[10])
              oneRow2Collect.touch_time = replaceAll(strTime,"-",":")
              // strTime = strTime.replace("时",":")
              // strTime = strTime.replace("分",":")
              // strTime = strTime.replace("秒",":")
              oneRow2Collect.file_size = Number(item[11])
              oneRow2Collect.chid_primary = item[12]
              oneRow2Collect.detect_algotype = item[13]
              oneRow2Collect.detect_bandwidth = item[14]
              oneRow2Collect.sample_rate = item[15]
              oneRow2Collect.estimate_bandwidth = item[16]
              oneRow2Collect.upFactor = item[17]
              oneRow2Collect.related_Len = item[18]
              oneRow2Collect.estimate_algotype = item[19]
              oneRow2Collect.fre_range = item[20]
              oneRow2Collect.time_range = item[21]
              oneRow2Collect.judege_threshold = item[22]
              
              sendExcel2Collect.push(oneRow2Collect)

              oneRow2Detect.path_id = Number(item[1])
              oneRow2Detect.collect_column.ch0_freq = Number(item[2])
              oneRow2Detect.collect_column.ch1_freq = Number(item[3])
              oneRow2Detect.collect_column.ch2_freq = Number(item[4])
              oneRow2Detect.collect_column.ch3_freq = Number(item[5])
              oneRow2Detect.collect_column.ch0_gain = Number(item[6])
              oneRow2Detect.collect_column.ch1_gain = Number(item[7])
              oneRow2Detect.collect_column.ch2_gain = Number(item[8])
              oneRow2Detect.collect_column.ch3_gain = Number(item[9])
              oneRow2Detect.collect_column.touch_time = replaceAll(strTime,"-",":")
              oneRow2Detect.collect_column.file_size = Number(item[11])
              oneRow2Detect.detect_column.chid_primary = item[12]
              oneRow2Detect.detect_column.detect_algotype = item[13]
              oneRow2Detect.detect_column.detect_bandwidth = item[14]
              oneRow2Detect.collect_column.sample_rate = item[15]
              oneRow2Detect.estimate_column.estimate_bandwidth = item[16]
              oneRow2Detect.estimate_column.up_factor = item[17]
              oneRow2Detect.estimate_column.related_len = item[18]
              oneRow2Detect.estimate_column.estimate_algotype = item[19]
              oneRow2Detect.estimate_column.freq_range = item[20]
              oneRow2Detect.estimate_column.time_range = item[21]
              oneRow2Detect.estimate_column.judge_threshold = Number(item[22])
              sendExcel2Detect.push(oneRow2Detect)
          }
        }
        }
      })
      
    }
    const replaceAll = (str, find, replace) => {
      return str.replace(new RegExp(find, 'g'), replace);
    }
    const handleFileExceed = async (files:any) => {
      uploadRef.value!.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      uploadRef.value!.handleStart(file);
      importData.file = file;
    }
</script>

<style>
.flex-grow {
  flex-grow: 1;
}
.el-table_header{
  background-color: #545c64;
}
.detectSetting{
  display: inline-block;
}
</style>
  